<?php

namespace App\Console\Commands;

use App\Exports\OldOrderExport;
use App\Model\OldOrder;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;

class ExportOrders2 extends Command
{
    const FILE_NAME = 'export.data.xlsx'; // you're default excel path

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'export:order2 {fileName?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'export order';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $fileName = $this->argument('fileName');

        if (null === $fileName) {
            $fileName = self::FILE_NAME;
        }

        $diffSkuArray = ['i-369b7e48', 'i-32ab5f32', 'i-2289ab50'];

        $this->output->writeln(sprintf("data row count: %d", OldOrder::query()->count()));
        $this->output->writeln("loadding...");
        $s = 1;

        OldOrder::query()->chunk(5000, function ($orderList) use ($fileName, $diffSkuArray, &$s) {
            $newData = [];
            $this->output->writeln("loaded ({$s})! now, we will dump data.");
            foreach ($orderList as $k => &$v) {

                $detail = json_decode($v['detail'], true);
                foreach ($detail as $key => $value) {
                    if (isset($value['commodity_code'])) {
                        if (in_array($value['commodity_code'], $diffSkuArray)) {
                            $newData[] = $v['code'];
                        }
                    }
                }
            }

            $this->output->writeln("dumped ({$s})! then we will store data into file.");

            if (empty($newData)) {
                $this->output->warning("empty data!");
            } else {
                Excel::store(new OldOrderExport($newData), $s . '_' . $fileName);
            }

            $s++;
        });

        $this->output->writeln("successfully!");
    }
}
